package com.srwl.mytx.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.bm.library.Info;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.smarx.notchlib.INotchScreen;
import com.smarx.notchlib.NotchScreenManager;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.LatLng;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.PickPictureAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.FileUpLoad;
import com.srwl.mytx.domain.Forward;
import com.srwl.mytx.domain.MyFile;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.map.GaodeLocationClient;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.ForwardService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.FileUtils;
import com.srwl.mytx.utils.GlideEngine;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.utils.SoftKeyboardFixerForFullscreen;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.PickPicturesListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 捐赠转发页面
 * 可以对捐赠进行转捐
 * 只有学校 地区 行业 这三种类型的主题的管理员有权限打开这个页面
 */
public class ForwardDonationActivity extends BaseActivity implements PickPictureAdapter.InteractionListener, PermissionsUtils.IPermissionsResult {
    private static final String TAG = "ForwardDonationActivity";
    public static final int REQUEST_CODE_LOCATION = 3;

    @BindView(R.id.tv_donation_balance)
    TextView tv_donationBalance;
    @BindView(R.id.tv_forward_count)
    TextView tv_forwardCount;
    @BindView(R.id.et_forward_amount)
    EditText et_forwardAmount;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.btn_search)
    Button btn_search;
    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;
    @BindView(R.id.tv_username)
    TextView tv_username;
    @BindView(R.id.ll_user)
    LinearLayout ll_user;
    @BindView(R.id.et_reason)
    EditText et_reason;
    @BindView(R.id.pick_picture_view)
    PickPicturesListView picturesListView;
    @BindView(R.id.btn_confirm)
    Button btn_confirm;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.rl_location)
    RelativeLayout rl_location;
    @BindView(R.id.tv_address)
    TextView tv_address;
    private GaodeLocationClient location;
    private boolean locationSuccess;
    private String str_address;

    private LatLng latLng;

    private Topic targetTopic;
    private User targetUser;
    private Double donationBalance;
    private int forwardSize;
    //视频封面图片
    private String framePicPath;
    //视频大小
    private int videoSize;
    private int pictureLimit = 9;//默认设置9张图片
    private int videoLimit = 1;//默认设置1个视频
    private ArrayList<MyFile> totalSelectFile = new ArrayList<>();//总的选择图片文件集合，包括本地的和远程的（历史文件）
    private ArrayList<MyFile> selectRemotePictures = new ArrayList<>();//选择的历史图片 文件
    private ArrayList<MyFile> selectRemoteVideos = new ArrayList<>();//选择的历史 视频文件
    private ArrayList<MyFile> selectLocalPictures = new ArrayList<>();//选择的本地 图片文件
    private ArrayList<MyFile> selectLocalVideos = new ArrayList<>();//选择的本地 视频文件
    private ArrayList<Photo> selectPhotos = new ArrayList<>();//本地圖片 path 集合
    private MoneyInputCheck moneyInputCheck;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_forward_donation);
        View statusBar = findViewById(R.id.status_bar);
        NotchScreenManager.getInstance().getNotchInfo(this, new INotchScreen.NotchScreenCallback() {
            @Override
            public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {

                if (notchScreenInfo.hasNotch) {
                    statusBar.setVisibility(View.GONE);
                } else {
                    //如果不是刘海屏，就设置为全屏
                    SoftKeyboardFixerForFullscreen.assistActivity(ForwardDonationActivity.this);
                    setupStartBar();
                    int statusBarHeight = Utils.getStatusBarHeight(ForwardDonationActivity.this);
                    if (statusBarHeight != 0) {
                        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
                        layoutParams.height = statusBarHeight;
                        statusBar.setLayoutParams(layoutParams);
                    }
                }

            }
        });
        targetTopic = getIntent().getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        ButterKnife.bind(this);
        picturesListView.init(totalSelectFile, this);
        donationBalance = targetTopic.getDonationBalance();
        tv_donationBalance.setText(Utils.moneyFormat(donationBalance));
        if (targetTopic.getForwardSize() != null) {
            forwardSize = targetTopic.getForwardSize();
        }
        tv_forwardCount.setText(Utils.numberFormat(forwardSize));
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchTargetUserInfo();
            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String forwardAmount = et_forwardAmount.getText().toString();

                if (targetUser == null) {
                    showToast(btn_confirm, "还没有设置受赠人");
                    return;
                }

                if (TextUtils.isEmpty(str_address)) {
                    showToast(btn_confirm, "还没有设置位置信息");
                    return;
                }

                ConfirmDialog confirmDialog = new ConfirmDialog(ForwardDonationActivity.this, "确认", "转发 " + forwardAmount + " 元给 " + targetUser.getUsername() + " ?", true);
                confirmDialog.show();
                confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        fileUpload(forwardAmount);
                    }
                });
            }
        });

        btn_confirm.setEnabled(true);

        initMoneyInputCheck();

        et_forwardAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                moneyInputCheck.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                moneyInputCheck.afterTextChanged(s);
            }
        });

    }

    void initMoneyInputCheck() {
        moneyInputCheck = new MoneyInputCheck(ForwardDonationActivity.this, 0.01, donationBalance, new MoneyInputCheck.InteractionListener() {
            @Override
            public void showErrorMessage(String message) {
                btn_confirm.setEnabled(false);
                et_forwardAmount.setError(message);
                et_forwardAmount.setTextColor(getResources().getColor(R.color.rp_money_red_light));
            }

            @Override
            public void waitInput() {
                btn_confirm.setEnabled(false);
                et_forwardAmount.setTextColor(getResources().getColor(R.color.rp_text_black));

            }

            @Override
            public void inputRight() {
                btn_confirm.setEnabled(true);
                et_forwardAmount.setTextColor(getResources().getColor(R.color.rp_text_black));

            }
        });
    }

    private void fileUpload(String forwardAmount) {
        FileUpLoad fileUpLoad = new FileUpLoad(ForwardDonationActivity.this, totalSelectFile, new FileUpLoad.InteractionListener() {
            @Override
            public void onShowToast(String content) {
                showToast(findViewById(R.id.btn_publish), content);
            }

            @Override
            public void onShowProgressBar(String content) {
                showProgressDialog(content);
            }

            @Override
            public void onHideProgressBar() {
                hideProgressDialog();
            }

            @Override
            public void onUploadComplete() {
                forwardDonation(forwardAmount);
            }
        });

        fileUpLoad.run();

    }

    private void forwardDonation(String forwardAmount) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        Forward forward = new Forward();
        forward.setAmount(Double.valueOf(forwardAmount));
        forward.settId(targetUser.getuId());
        forward.setoId(targetTopic.getId());
        forward.setReason(et_reason.getText().toString());
        forward.setAddress(str_address);
        forward.setLocation(latLng);
        List<MyFile> uploadList = new ArrayList<>();
        for (MyFile myFile : totalSelectFile) {
            if (myFile.getStatus() != MyFile.FILE_STATUS_UPLOAD_FAIL) {//只要不是上传失败的，都给保存到服务端
                uploadList.add(myFile);
            }
        }
        forward.setMyFileList(uploadList);
        showProgressDialog("正在保存...");
        btn_confirm.setEnabled(false);
        RetrofitManager.getInstance().createRequest(ForwardService.class)
                .forwardDonation(forward)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideProgressDialog();
                        CommonResult result = response.body();
                        btn_confirm.setEnabled(true);
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(btn_confirm, getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            btn_confirm.setEnabled(true);
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(btn_confirm, getString(R.string.balance_not_enough));
                                    break;
                                case Constant.DONATION_FORWARD_NO_AUTHORIZATION:
                                    showToast(btn_confirm, "权限不足");
                                    break;
                                default:
                                    showToast(btn_confirm, getString(R.string.system_busy));
                            }
                            return;
                        }
                        btn_confirm.setEnabled(false);
                        Log.d(TAG, "onResponse: 转发捐赠完成");
                        updateFileStatus(uploadList);
                        //   donationBalance = ((BigDecimal) result.getData()).doubleValue();
                        JSONObject data = (JSONObject) result.getData();
                        donationBalance = data.getDouble("donationBalance");
                        String forwardId = data.getString("forwardId");
                        forward.setfId(forwardId);
                        forwardSize++;
                        initMoneyInputCheck();//在捐赠完成后，捐赠余额改变，需要重新设置金额限制的上限
                        tv_donationBalance.setText(Utils.moneyFormat(donationBalance));
                        tv_forwardCount.setText(Utils.numberFormat(forwardSize));
                        et_forwardAmount.setText("");
                        moneyInputCheck.setMaxLimit(donationBalance);
                        //返回页面进行刷新金额
                        Double donationBalance = targetTopic.getDonationBalance();
                        targetTopic.setDonationBalance(donationBalance - Double.valueOf(forwardAmount));
                        Integer donationSize = targetTopic.getDonationSize().intValue() + 1;
                        targetTopic.setDonationSize((double) donationSize);
                        targetTopic.setForwardSize(forwardSize);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TOPIC, targetTopic));
                        ConfirmDialog confirmDialog = new ConfirmDialog(ForwardDonationActivity.this, "转发完成", "去看看转发详情？", true);
                        confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                            @Override
                            public void confirm() {
                                List<String> pictures = new ArrayList<>();
                                for (MyFile myFile : uploadList) {
                                    if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                                        pictures.add(myFile.getUrl());
                                    } else {
                                        forward.setVideo(myFile.getUrl());
                                        forward.setVideoCover(myFile.getVideoCover());
                                    }
                                }
                                forward.setPictures(pictures);
                                forward.setManagerUser(UserProfileManager.getInstance().getLoginUserInfo());
                                forward.setTargetUser(targetUser);
                                startActivity(new Intent(ForwardDonationActivity.this, ForwardDetailsActivity.class).putExtra(Constant.EXTRA_INFO_FORWARD, forward));
                            }
                        });
                        confirmDialog.show();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        btn_confirm.setEnabled(true);
                        hideProgressDialog();
                    }
                });
    }

    public void searchTargetUserInfo() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        hideSoftKeyboard();
        final String name = et_phone.getText().toString();
//        final String saveText = searchBtn.getText().toString();
//
//        if (getString(R.string.button_search).equals(saveText)) {
        if (TextUtils.isEmpty(name)) {
            showToast(et_phone, "请输入对方电话号码");

            return;
        }

        final ProgressDialog pd = new ProgressDialog(this);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage("正在查找...");

        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .searchContact(name)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        pd.dismiss();

                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.d(TAG, response.code() + response.message());
                            showToast(et_phone, getString(R.string.system_busy));
                            return;
                        }
                        if (commonResult.isError()) {
                            switch (commonResult.getStatus()) {
                                case Constant.MOBILE_INVALID:
                                    showToast(et_phone, "没有对应的用户信息，请检查输入的手机号是否正确");
                                    break;

                                case Constant.PHONE_NUMBER_FORMAT_ERROR:
                                    showToast(et_phone, getString(R.string.phone_number_type_error));
                                    break;
                                default:
                                    showToast(et_phone, getString(R.string.system_busy));


                            }
                            return;
                        }

                        JSONObject jsonObject = (JSONObject) commonResult.getData();
                        targetUser = jsonObject.toJavaObject(User.class);
                        showTargetUserInfo();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        pd.dismiss();
                        showToast(et_phone, getString(R.string.system_busy));
                    }
                });

    }

    public void showTargetUserInfo() {
        ll_user.setVisibility(View.VISIBLE);
        if (targetUser.getUsername() != null) {
            tv_username.setText(targetUser.getUsername());
        } else {
            tv_username.setText(targetUser.getNick());
        }
        if (targetUser.getAvatar() != null) {
            String avatarUrl = targetUser.getAvatar();
//            Glide.with(ForwardDonationActivity.this)
//                    .load(avatarUrl).diskCacheStrategy(DiskCacheStrategy.ALL)
//                    .placeholder(R.drawable.fx_icon_camera)
//                    .into(iv_avatar);

            GlideLoadUtils.glideLoad(this, avatarUrl, iv_avatar, R.drawable.tx_default_avatar_1);
        }
    }

    @Override
    public void onSelectRemoteFile() {
        ArrayList<MyFile> historySelectFile = new ArrayList<>();
        historySelectFile.addAll(totalSelectFile);//添加总的
        historySelectFile.removeAll(selectLocalVideos);
        historySelectFile.removeAll(selectLocalPictures);
        MyFileSelectActivity.startActivity(this, videoLimit - selectLocalVideos.size(), pictureLimit - selectLocalPictures.size(), false, historySelectFile, PublishTopicActivity.REQUEST_CODE_PICTURE_CHOOSE);

    }

    @Override
    public void onPickNewPicture(int position) {
//        Matisse.from(ForwardDonationActivity.this)
//                .choose(MimeType.ofImage())
//                .countable(true)
//                .showSingleMediaType(true)
//                .maxSelectable(pictureLimit - selectRemotePictures.size())
//                .theme(R.style.choose_pictures_style)
//                // .addFilter(new (320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(
//                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//                .thumbnailScale(0.85f)
//                .imageEngine(new GlideEngine())
//                .forResult(REQUEST_CODE_PICTURE_CHOOSE);

        // TODO: 2019/7/4

        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                .setFileProviderAuthority("com.srbl.mytx.fileProvider")
                .setSelectedPhotos(selectPhotos)
                .setCount(9)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        selectPhotos = photos;
                        totalSelectFile.removeAll(selectLocalPictures);
                        selectLocalPictures.clear();
                        for (Photo photo : photos) {
                            selectLocalPictures.add(new MyFile(photo.uri, MyFile.FILE_TYPE_PICTURE, MyFile.FILE_STATUS_LOCAL));
                        }
                        totalSelectFile.addAll(selectLocalPictures);
                        picturesListView.refresh();
                    }
                });


    }

    @Override
    public void onShowBigImage(MyFile targetPictureFile, Info info) {

    }

    @Override
    public void onCreateVideo(View view, int position) {
        startRecordVideo();
    }

    @Override
    public void onShowVideo(MyFile targetVideoFile, int position) {
        //展示短视频
        showVideo(targetVideoFile.getUrl());
    }

    @Override
    public void onPictureRemove(int position, MyFile targetPictureFile) {
        if (targetPictureFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemotePictures.remove(targetPictureFile);
        } else {
            selectLocalPictures.remove(targetPictureFile);
            //清除掉已选文件记录
            for (int i = 0; i < selectPhotos.size(); i++) {
                if (selectPhotos.get(i).uri.equals(targetPictureFile.getUri())) {
                    selectPhotos.remove(i);
                    break;
                }
            }
        }
        // bigPicturePageView.refresh();
    }

    @Override
    public void onVideoRemove(int position, MyFile targetVideoFile) {
        if (targetVideoFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemoteVideos.remove(targetVideoFile);
        } else {
            selectLocalVideos.remove(targetVideoFile);
        }
        //  bigPicturePageView.refresh();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        switch (requestCode) {
            case PublishTopicActivity.REQUEST_CODE_PICTURE_CHOOSE:

                ArrayList<MyFile> pictureFiles = data.getParcelableArrayListExtra("pictureFiles");
                ArrayList<MyFile> videoFiles = data.getParcelableArrayListExtra("videoFiles");
                totalSelectFile.removeAll(selectRemoteVideos);
                selectRemoteVideos.clear();
                if (videoFiles != null && videoFiles.size() != 0) {
                    selectRemoteVideos.addAll(videoFiles);
                    totalSelectFile.addAll(0, videoFiles);
                    // picturesListView.refreshVideoItem(videoFiles.get(0));
                }
                totalSelectFile.removeAll(selectRemotePictures);
                selectRemotePictures.clear();
                if (pictureFiles != null && pictureFiles.size() != 0) {
                    selectRemotePictures.addAll(pictureFiles);
                    totalSelectFile.addAll(pictureFiles);
                }
                picturesListView.refresh();
                break;

            case PublishTopicActivity.REQUEST_CODE_RECORD_VIDEO:

                framePicPath = data.getStringExtra("coverPath");
                //视频本地路径
                String localVideoPath = data.getStringExtra("videoPath");
                videoSize = data.getIntExtra("videoSize", 0);
                totalSelectFile.removeAll(selectLocalVideos);
                selectLocalVideos.clear();
                MyFile localVideoFile = new MyFile(localVideoPath, framePicPath,MyFile.FILE_TYPE_VIDEO, MyFile.FILE_STATUS_LOCAL);
                selectLocalVideos.add(localVideoFile);
                totalSelectFile.addAll(0, selectLocalVideos);//插到第一个的位置
                picturesListView.refresh();
                break;
            case REQUEST_CODE_LOCATION:
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);
                if (latLng == null) {
                    latLng = new LatLng();
                }
                latLng.setLatitude(latitude);
                latLng.setLongitude(longitude);
                str_address = data.getStringExtra("address");
                tv_address.setText(str_address);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                    }
//                });
                Log.d(TAG, "onActivityResult: 收到定位回传");
                break;

        }
    }

    private void startRecordVideo() {
        long SDCardRemainMB = FileUtils.getSDFreeSize();
        if (SDCardRemainMB >= 0L && SDCardRemainMB < 2L) {
            showToast(getString(R.string.aliwx_no_enough_sdcard_size));
            return;
        }

        //startActivityForResult(new Intent(this, VideoRecordActivity.class), PublishTopicActivity.REQUEST_CODE_RECORD_VIDEO);
        VideoRecordActivityV3.startActivity(this, PublishTopicActivity.REQUEST_CODE_RECORD_VIDEO, true);

    }

    private void showVideo(String videoPath) {
        Uri uri = Uri.parse("http://svideo.m.taobao.com/av/implayer.html");
        Intent intent = new Intent("android.intent.action.VIEW", uri, ForwardDonationActivity.this, MyVideoPlayActivity.class);
        intent.putExtra("videoPath", videoPath);
        intent.putExtra("framePicPath", framePicPath);
        intent.putExtra("videoSize", videoSize);
        startActivity(intent);
    }

    /**
     * 保存到服务后，把已经保存的图片的状态设置为 远程图片
     * 不然连续发布，服务端把图片当成新上传图片传，插入到数据库被报ID重复的错
     *
     * @param uploadList
     */
    private void updateFileStatus(List<MyFile> uploadList) {
        for (MyFile myFile : uploadList) {
            if (myFile.getStatus() == MyFile.FILE_STATUS_UPLOAD_SUCCESS) {
                myFile.setStatus(MyFile.FILE_STATUS_REMOTE);
                //从本地文件选择集合中  移动到  远程文件选择集合中，并刷新
                if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                    selectLocalPictures.remove(myFile);
                    selectRemotePictures.add(myFile);
                } else {
                    selectLocalVideos.remove(myFile);
                    selectRemoteVideos.add(myFile);
                }
                picturesListView.refresh();
            }
        }
    }

    @OnClick(R.id.rl_location)
    void location() {
        Intent intent = new Intent(ForwardDonationActivity.this, PickLocationMapActivity.class);
        if (latLng != null) {
            intent.putExtra(PickLocationMapActivity.EXTRA_DATA_LATITUDE, latLng.getLatitude());
            intent.putExtra(PickLocationMapActivity.EXTRA_DATA_LONGITUDE, latLng.getLongitude());
        }
        startActivityForResult(intent, REQUEST_CODE_LOCATION);
    }


    @Override
    protected void onStart() {
        super.onStart();
        String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
        PermissionsUtils.getInstance().checkPermissions(this, permissions, this);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onGranted() {
        //只需定位一次，不然当选择地位地址返回这个activity 之后，会重新调用定位，
        if (!locationSuccess) {
            //  initLocation();
        }
    }

    private void initLocation() {
        location = new GaodeLocationClient(this,true);
        location.setLocationListener(new GaodeLocationClient.LocationListener() {
            @Override
            public void locationSuccess(AMapLocation location) {
                locationSuccess = true;
                latLng = new LatLng(location.getLatitude(), location.getLongitude());
                str_address = location.getAddress();
                tv_address.setText(str_address);
            }
        });
    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        StringBuilder tips = new StringBuilder();
        for (String permission : deniedPermissionList) {
            if (Manifest.permission.ACCESS_FINE_LOCATION.equals(permission)) {
                tips.append("[位置] ");
            } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permission)) {
                tips.append("[储存空间] ");
            } else if (Manifest.permission.RECORD_AUDIO.equals(permission)) {
                tips.append("[麦克风] ");
            } else if (Manifest.permission.CAMERA.equals(permission)) {
                tips.append("[相机] ");
            }
        }
        ConfirmDialog dialog = new ConfirmDialog(ForwardDonationActivity.this, "提醒", "使用 " + tips + "的权限被禁止，去设置？", "去设置", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });
        dialog.setCancelListener(new ConfirmDialog.CancelListener() {
            @Override
            public void cancel() {
                finish();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PermissionsUtils.getInstance().clear();
    }
}
